package study.jqp.com.studydemo.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.sql.SQLData;

public class DBHelper  extends SQLiteOpenHelper {

    static final String DATABASE_NAME  = "MyDatabase.db";

    static final String TAB_NAME  = "users";

    public static final String FIELD_NAME  = "name";
    public static final String FIELD_PASSWORD  = "password";
    public static final String FIELD_AGE  = "age";

    SQLiteDatabase db;


    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);  // 参数为数据库名称，版本号
        db=getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        String createTableSQL = "CREATE TABLE "+TAB_NAME+" (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                +FIELD_NAME+" TEXT, "
                +FIELD_PASSWORD+" TEXT,"
                +FIELD_AGE+" INTEGER)";
        sqLiteDatabase.execSQL(createTableSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    public long addUser(ContentValues values){
        return db.insert(TAB_NAME,null,values);

    }
    public int updataByName(String name,ContentValues values){
        return db.update(TAB_NAME,values,FIELD_NAME+" = ?",new String[]{name});
    }

    public int detele(String name){
        return db.delete(TAB_NAME,FIELD_NAME+" = ?",new String[]{name});
    }

    public String findpasswordByName(String name){
        String pwd = null;

        String selection = FIELD_NAME+" = ?";
        Cursor cursor = db.query(TAB_NAME, new String[]{"id", "name", "age"}, selection, null, null, null, null);
        if (cursor!=null&&cursor.moveToFirst()){
            pwd = cursor.getString(2);
            cursor.close();
        }
        return pwd;
    }

    public String findPasswordByName(String name){
        String pwd = null;
        String selection = FIELD_NAME + " = ?";
        Cursor cursor = db.query(TAB_NAME, null, selection, new String[]{name}, null, null, null);
        if (cursor!=null && cursor.moveToFirst()){
            pwd = cursor.getString(2);
            cursor.close();
        }
        return pwd;
    }

    public void closeDB(){

        if(db!=null&&db.isOpen()){
            db.close();
        }
    }
}
